package common.convert;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @Desc: "装饰者模式 ，对写出和写入的消息进行自定义的装饰"
 * @Author: caixiang
 * @DATE: 2020/9/22 14:29
 */
public class RabbitMessageConvert implements MessageConverter {
    private GenericMessageConvert delegate;
    private final String delaultExpire = String.valueOf(24 * 60 * 60 *1000);

    public RabbitMessageConvert(GenericMessageConvert messageConvert){
        this.delegate = messageConvert;
    }

    //把api.Message写出 可以装饰
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        //默认过期时间设置为1天
        messageProperties.setExpiration(delaultExpire);
        //.........下面可以设置许多message属性
        return this.delegate.toMessage(o,messageProperties);
    }

    //把amqp.Message写入 可以装饰（转成api.message）
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        api.Message message1 = (api.Message) this.delegate.fromMessage(message);
        return message1;
    }
}